<script setup lang="ts">
import { ref } from "vue";
import { sendEmailApi, registerApi, IRegister } from "@/api/auth";
import { showToast } from "vant";
import { useRouter } from "vue-router";

const router = useRouter();

const formData = ref<IRegister>({
  code: "",
  confirmPassword: "",
  email: "",
  password: "",
  username: "",
});

const onSubmit = () => {
  registerApi(formData.value as IRegister).then(() => {
    router.push("/login");
  });
};

const toLogin = () => {
  router.push("/login");
};

const time = ref(0);
const text = ref("获取验证码");
const sendCode = async () => {
  if (time.value > 0) return;
  if (!formData.value.email) return showToast("请输入邮箱");
  const res = await sendEmailApi({ email: formData.value.email });
  console.log(res.data.msg);
  time.value = 60;
  const timer = setInterval(() => {
    time.value--;
    text.value = `${time.value}s`;
    if (time.value <= 0) {
      clearInterval(timer);
      text.value = "获取验证码";
    }
  }, 1000);
};
</script>

<template>
  <div class="login">
    <van-nav-bar title="注册" />

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="formData.username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="formData.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="formData.confirmPassword"
          type="password"
          name="confirmPassword"
          label="确认密码"
          placeholder="确认密码"
          :rules="[{ required: true, message: '请填写确认密码' }]"
        />
        <van-field
          v-model="formData.email"
          name="email"
          label="邮箱"
          placeholder="邮箱"
          :rules="[{ required: true, message: '请填写邮箱' }]"
        />
        <van-field
          v-model="formData.code"
          name="code"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        >
          <template #button>
            <van-button
              :disabled="time > 0"
              size="small"
              type="primary"
              @click="sendCode"
              >{{ text }}</van-button
            >
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          注册
        </van-button>
      </div>

      <div class="login__methods">
        <span class="login__methods-account" @click="toLogin"
          >已有账号去登录</span
        >
      </div>
    </van-form>
  </div>
</template>
